<template>
  <div class="app-content-body fade-in-up ng-scope">
    <div class="fade-in ng-scope">
      <div class="bg-light lter b-b wrapper-md ng-scope table-page-title">
        <h1 class="m-n font-thin h3">用户管理页</h1>
      </div>
      <div class="wrapper-md ng-scope" v-loading="tableLoading">
        <div class="panel panel-default m-b-none">
          <div class="panel-heading table-list-title">
            <span>用户数据</span>
            <el-popover
              ref="delUserPopover"
              placement="bottom"
              width="160"
              v-model="delShow">
              <p>选中用户可包含在其他页中，确认删除吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="delShow = false">取消</el-button>
                <el-button type="primary" size="mini" @click="delMore()">确定</el-button>
              </div>
            </el-popover>
            <el-button-group>
              <el-button v-auth="'VUser:tab:add'" type="info" @click="dialogUserAdd = true;" size="small" icon="plus">添加</el-button>
              <el-button v-auth="'VUser:tab:del'" type="danger" v-popover:delUserPopover size="small" icon="delete">删除</el-button>
            </el-button-group>
            <el-dialog ref="addUserDialog" title="用户添加" size="large" custom-class="el-dialog--width--75" v-scrollclick top="7%" v-model="dialogUserAdd">
              <addUser v-on:addSuccessState="search"></addUser>
            </el-dialog>
            <el-dialog ref="editUserDialog" @close="editId = null" title="用户修改" size="large" custom-class="el-dialog--width--75" v-scrollclick top="7%" v-model="dialogUserEdit">
              <editUser v-on:editSuccessState="fetchData" :edit-id="editId"></editUser>
            </el-dialog>
          </div>
          <div class="panel m-b0">
            <div class="row padding-top15 padding-b7 m-l-none m-r-none">
              <el-form :model="userSearch" ref="userSearch">
                <div class="d-h form-horizontal">
                  <div class="col-sm-3 m-l-sm">
                    <el-input v-model="userSearch.loginName" placeholder="请输入用户账号(不支持模糊查询)"></el-input>
                  </div>
                  <div class="col-sm-3 m-l-sm">
                    <el-input v-model="userSearch.name" placeholder="请输入用户名称"></el-input>
                  </div>
                  <div class="input-group col-sm-2">
                    <span class="input-group-btn p-t-4 p-l-sm">
                      <el-button-group>
                        <el-button type="primary" :loading="ifSub" @click="search()" size="small" icon="search">搜索</el-button>
                        <el-button type="primary" size="small" @click="userSearch.loginName='';userSearch.name='';" icon="minus">重置</el-button>
                      </el-button-group>
                    </span>
                  </div>
                </div>
              </el-form>
            </div>
          </div>
          <tabCollapseProductNavbar v-on:tableHeightChange="tableHeightChange" :height="50"></tabCollapseProductNavbar>
          <div class="m-t--49">
            <el-table :data="pageResult.voList" :height="tableHeight"
                      row-key="id" @header-click="headerClick" @sort-change="sortChange"
                      @selection-change="handleSelectionChange"
                      :default-sort="{prop:'creatTime',order:'descending'}"
                      stripe style="width: 100%">
              <el-table-column
                type="selection"
                :reserve-selection="booleanTrue"
                width="55">
              </el-table-column>
              <el-table-column type="expand">
                <template scope="props">
                  <el-form label-position="right" inline class="table-expand">
                    <el-form-item label="用户 ID">
                      <span>{{ props.row.id }}</span>
                    </el-form-item>
                    <el-form-item label="用户名">
                      <span>{{ props.row.loginName }}</span>
                    </el-form-item>
                    <el-form-item label="姓名">
                      <span>{{ props.row.name }}</span>
                    </el-form-item>
                    <el-form-item label="昵称">
                      <span>{{ props.row.nickName }}</span>
                    </el-form-item>
                    <el-form-item label="部门">
                      <span>{{ props.row.department.fullName }}</span>
                    </el-form-item>
                    <el-form-item label="类型">
                      <paramsText :options="paramsOptions" :choose="props.row.types"></paramsText>
                    </el-form-item>
                    <el-form-item label="状态">
                      <el-tag
                        :type="props.row.state? 'success' : 'danger'"
                        close-transition>{{props.row.state?'启用':'禁用'}}
                      </el-tag>
                    </el-form-item>
                    <el-form-item label="安全级别">
                      <span>{{ props.row.safeLeveler }}</span>
                    </el-form-item>
                    <el-form-item label="创建人">
                      <span>{{ props.row.creater }}</span>
                    </el-form-item>
                    <el-form-item label="创建时间">
                      <span>{{ props.row.creatTime }}</span>
                    </el-form-item>
                    <el-form-item label="备注">
                      <span>{{ props.row.memo }}</span>
                    </el-form-item>
                  </el-form>
                </template>
              </el-table-column>
              <el-table-column
                label="头像" width="120"
                prop="headImg" align="center">
                <template scope="scope">
                  <div class="m-sm">
                    <img class="avatar"
                         :src="headImg(scope.row.headImg)"
                         width="50px" height="50px">
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="账号" align="center"
                prop="loginName" :sortable="'custom'"
                width="180">
              </el-table-column>
              <el-table-column
                label="姓名" align="center"
                min-width="130" :sortable="'custom'"
                prop="name">
              </el-table-column>
              <el-table-column
                label="状态" align="center"
                width="85"
                :sortable="'custom'"
                prop="state">
                <template scope="scope">
                  <el-tag
                    :type="scope.row.state? 'success' : 'danger'"
                    close-transition>{{scope.row.state?'启用':'禁用'}}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column
                label="安全级别" align="center"
                width="115" :sortable="'custom'"
                prop="safeLeveler">
                <template scope="scope">
                  <div class="text-right">
                    {{scope.row.safeLeveler}}
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="创建人" align="center"
                min-width="160"
                :sortable="'custom'"
                prop="creater">
              </el-table-column>
              <el-table-column
                label="创建时间" align="center"
                width="113" :sortable="'custom'"
                prop="creatTime">
              </el-table-column>
              <el-table-column
                :fixed="option"
                label="操作" align="center"
                width="200">
                <template scope="scope">
                  <el-button
                    type="info" :plain="true"
                    size="small" @click="dialogUserEdit = true;editId = scope.row.id;">
                    编辑
                  </el-button>
                  <el-popover
                    placement="top"
                    width="160" trigger="click">
                    <p>确认重置用户密码吗？</p>
                    <div style="text-align: right; margin: 0">
                      <el-button size="mini" type="text" @click="cancel()">取消</el-button>
                      <el-button type="primary" size="mini" @click="resetPassword()">确定</el-button>
                    </div>
                    <div slot="reference" style="display: inline">
                      <el-button type="warning" @click="resetId = scope.row.id" :plain="true" size="small">重置密码</el-button>
                    </div>
                  </el-popover>
                  <el-popover
                    placement="top"
                    width="160" trigger="click">
                    <p>数据无价，确认删除吗？</p>
                    <div style="text-align: right; margin: 0">
                      <el-button size="mini" type="text" @click="cancel()">取消</el-button>
                      <el-button type="primary" size="mini" @click="delOne()">确定</el-button>
                    </div>
                    <div slot="reference" style="display: inline">
                      <el-button type="danger" @click="delOneClick(scope.row.id)" :plain="true" size="small">删除</el-button>
                    </div>
                  </el-popover>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <footer class="panel-footer text-right">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="userSearch.nowPage"
              :page-sizes="[30, 60, 90, 120]"
              :page-size="userSearch.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pageResult.totalRecord">
            </el-pagination>
          </footer>
        </div>
      </div>
    </div>
    <div style="display: none">{{tableHeight_}}</div>
  </div>
</template>
<script>

  import TabCollapseProductNavbar from '../../../common/tabCollapseProductNavbar.vue'
  import Vue from 'vue'
  import {SERVICE_URLS} from '../../../../config/service.url'
  import {ROUTE_URL} from '../../../../router/routes'
  import {updateUserChoose} from './update.choose'
  import AddUser from './add.vue'
  import EditUser from './edit.vue'
  import ParamsText from '../../../common/paramsText.vue'

  export default{
    data(){
      return {
        booleanTrue: true,
        delUserLoading: false,
        delShow: false,
        ifSub: false,
        paramsOptions: [],
        dialogUserAdd: false,
        dialogUserEdit: false,
        tableLoading: false,
        option: "right",
        userSearch: {
          loginName: "",
          name: "",
          "department.id": "",
          state: null,
          nowPage: 1,
          pageSize: 30,
          orderbys: null,
          orderbysDirection: null,
        },
        pageResult: {
          totalRecord: 0,
          voList: []
        },
        multipleSelection: [],
        delId: null,
        editId: null,
        resetId: null,
        tableHeight: 0,
        basicHeight: 248,
      }
    },
    computed: {
      tableHeight_(){
        this.tableHeight = this.$store.state.bodyHeight - this.basicHeight;
        return this.$store.state.bodyHeight;
      }
    },
    beforeRouteLeave (to, from, next) {
      if (to.path != ROUTE_URL.user.center.absolutePath) {
        this.$store.commit('userDepartmentChooseStateReset');
        next();
      }
    },
    created(){
      this.$store.commit('navDefaultActiveChange', ROUTE_URL.user.center.absolutePath);
      //初始化一些数据 动态获取用户类型数据
      const self = this;
      Vue.submit(self, {
        url: SERVICE_URLS.params.select,
        noTips: true,
        loading: "no",
        params: {
          id: "4-1"
        },
        callback(data){
          self.paramsOptions = data.body;
        }
      }, Vue)
    },
    mounted(){
      $(".el-table__body-wrapper").scroll(function () {
        $(this).click()
      });
      this.$store.commit('userAddDialogUpdate', this.$refs.addUserDialog);
      this.$store.commit('userEditDialogUpdate', this.$refs.editUserDialog);
    },
    watch: {
      '$route': 'search'
    },
    methods: {
      //添加搜索条件隐藏需要使用
      tableHeightChange(val){
        this.basicHeight = this.basicHeight - val;
        this.tableHeight = this.tableHeight + val;
      },
      //处理照片显示
      headImg(url){
        if (url && url != "") {
          return url + (url.indexOf("?") == -1 ? "?" : "|") + "imageView2/1/w/100/h/100";
        }
        return ""
      },
      //每页展示条数变化
      handleSizeChange(val) {
        this.userSearch.pageSize = val;
        //这里可能会出现获取两次数据行为
        this.fetchData();
      },
      //上一页、下一页、跳转能页数变化触发
      handleCurrentChange(val) {
        this.userSearch.nowPage = val;
        this.fetchData();
      },
      //checkbox选择触发事件
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      //表头th点击时触发事件，目前只做'操作'列fixed='right'
      headerClick(column, event){
        if (column.label === '操作') {
          this.option = ( this.option == '' ? 'right' : '')
        }
      },
      //单项删除去掉
      cancel(){
        document.getElementById('app').click();
      },
      //多项删除方法
      delMore(){
        this.delShow = false;
        let idList = [];
        for (let one in this.multipleSelection) {
          idList.push(this.multipleSelection[one].id)
        }
        const self = this;
        this.del(SERVICE_URLS.user.deleteMore, 'data', idList, function () {
          self.multipleSelection = [];
        });
      },
      //单项删除点击
      delOneClick(id){
        this.delId = id;
      },
      //单项删除方法
      delOne(){
        this.cancel();
        this.del(SERVICE_URLS.user.delete, "params", {
          id: this.delId
        });
      },
      //删除http请求实现
      del(url, type, params, callback){
        this.tableLoading = true;
        this.$store.commit('cacheDataUpdate', {
          name: 'sysUserTableLoading',
          value: true
        });
        const self = this;
        let config = {
          url: url,
          loading: "tableLoading",
          callback(data){
            self.fetchData();
            self.$store.commit('cacheDataUpdate', {
              name: 'sysUserTableLoading',
              value: false
            });
            if (callback) {
              callback();
            }
          }
        };
        config[type] = params;
        Vue.submit(self, config, Vue)
      },
      //排序改变触发事件
      sortChange(val){
        if (val.prop) {
          this.userSearch.orderbys = val.prop;
          this.userSearch.orderbysDirection = val.order.replace("ending", "");
        } else {
          this.userSearch.orderbys = null;
          this.userSearch.orderbysDirection = null;
        }
        this.fetchData();
      },
      //执行检索
      search(){
        if (this.userSearch.nowPage == 1) {
          this.fetchData();
        } else {
          //分页组件自动触发数据抓取
          this.userSearch.nowPage = 1;
        }
      },
      //抓取数据实现
      fetchData(){
        this.userSearch["department.id"] = this.$route.params.pId;
        if (this.userSearch["department.id"] && this.userSearch["department.id"] != "") {
          const self = this;
          Vue.submit(self, {
            url: SERVICE_URLS.user.search,
            data: self.userSearch,
            noTips: true,
            callback(data){
              self.userSearch.pageSize = data.body.pageSize;
              self.userSearch.nowPage = data.body.nowPage;
              self.pageResult.totalRecord = data.body.totalRecord;
              self.pageResult.voList = data.body.voList
            }
          }, Vue);
          //为了保证后退时树能自动选择
          updateUserChoose(self, this.userSearch["department.id"]);
          //触发用户添加组件中默认选中部门事件
          this.$store.commit('userAddStateUpdate');
        }
      },
      //重置密码
      resetPassword(){
        this.cancel();
        Vue.submit(this, {
          url: SERVICE_URLS.user.reset,
          params: {
            id: this.resetId
          },
          loading: "no"
        }, Vue)
      }
    },
    components: {
      TabCollapseProductNavbar, AddUser, ParamsText, EditUser
    }
  }
</script>
